package com.adong.tv.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.leanback.app.BrowseSupportFragment;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.HeaderItem;
import androidx.leanback.widget.ListRow;
import androidx.leanback.widget.ListRowPresenter;
import androidx.leanback.widget.OnItemViewClickedListener;
import androidx.leanback.widget.OnItemViewSelectedListener;
import androidx.leanback.widget.Presenter;
import androidx.leanback.widget.Row;
import androidx.leanback.widget.RowPresenter;
import androidx.lifecycle.ViewModelProvider;

import com.adong.tv.R;
import com.adong.tv.model.ApiSource;
import com.adong.tv.model.Category;
import com.adong.tv.model.Movie;
import com.adong.tv.ui.DetailActivity;
import com.adong.tv.ui.presenter.ApiPresenter;
import com.adong.tv.ui.presenter.MovieCardPresenter;
import com.adong.tv.ui.viewmodel.MainViewModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主界面Fragment
 */
public class MainFragmentbak extends BrowseSupportFragment {
    
    private static final int CATEGORY_ALL = 0;
    
    private MainViewModel viewModel;
    private ArrayObjectAdapter rowsAdapter;
    private final Map<Integer, ArrayObjectAdapter> categoryAdapters = new HashMap<>();
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        viewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
        setupUI();
        setupEventListeners();
        loadData();
    }
    
    /**
     * 设置UI
     */
    private void setupUI() {
        // 设置标题
        setTitle(getString(R.string.app_name));
        
        // 设置搜索功能
        setHeadersState(HEADERS_ENABLED);
//        setHeadersState(HEADERS_DISABLED);
        setHeadersTransitionOnBackEnabled(true);
//        setHeadersVisibility(HEADERS_VISIBLE); // 确保 Headers 始终显示
        
        // 设置背景
//        Drawable background = ContextCompat.getDrawable(requireContext(), R.drawable.default_background);
        setBrandColor(ContextCompat.getColor(requireContext(), R.color.primary_dark));
        
        // 设置适配器
        rowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
        setAdapter(rowsAdapter);
        
        // 添加顶部的API切换行
        HeaderItem apiHeader = new HeaderItem(0, "选择数据源");
        ArrayObjectAdapter apiAdapter = new ArrayObjectAdapter(new ApiPresenter());
        for (ApiSource apiSource : viewModel.getAllApiSources()) {
            apiAdapter.add(apiSource);
        }
        rowsAdapter.add(new ListRow(apiHeader, apiAdapter));
    }
    
    /**
     * 设置事件监听器
     */
    private void setupEventListeners() {
        // 设置点击事件
        setOnItemViewClickedListener(new OnItemViewClickedListener() {
            @Override
            public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
                if (item instanceof Movie) {
                    Movie movie = (Movie) item;
                    Intent intent = new Intent(getActivity(), DetailActivity.class);
                    intent.putExtra(DetailActivity.EXTRA_MOVIE_ID, movie.getVodId());
                    startActivity(intent);
                } else if (item instanceof ApiSource) {
                    ApiSource apiSource = (ApiSource) item;
                    viewModel.switchApiSource(apiSource);
                    Toast.makeText(getContext(), "已切换到 " + apiSource.getDesc() + " 数据源", Toast.LENGTH_SHORT).show();
                    
                    // 刷新数据
                    loadData();
                }
            }
        });
        
        // 设置选择事件
        setOnItemViewSelectedListener(new OnItemViewSelectedListener() {
            @Override
            public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
                if (item instanceof Movie) {
                    // 可以在这里处理预览或其他效果
                }
            }
        });
    }
    
    /**
     * 加载数据
     */
    private void loadData() {
        // 清除现有的电影行
        List<ListRow> rowsToRemove = new ArrayList<>();
        for (int i = 0; i < rowsAdapter.size(); i++) {
            Object item = rowsAdapter.get(i);
            if (item instanceof ListRow) {
                ListRow row = (ListRow) item;
                if (row.getHeaderItem().getId() != 0) { // 不是API源行
                    rowsToRemove.add(row);
                }
            }
        }
        
        for (ListRow row : rowsToRemove) {
            rowsAdapter.remove(row);
        }
        
        categoryAdapters.clear();
        
        // 加载分类
        viewModel.getCategories().observe(getViewLifecycleOwner(), result -> {
            // 打印 result 数据
            Log.d("MainFragment", "loadData: " + result.getData());
            if (result.isSuccess() && result.getData() != null) {
                setupCategories(result.getData());
            } else {
                Toast.makeText(getContext(), "加载分类失败: " + result.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    /**
     * 设置分类
     * @param categories 分类列表
     */
    private void setupCategories(List<Category> categories) {
        // 添加"全部"分类
        HeaderItem allHeader = new HeaderItem(CATEGORY_ALL, "全部");
        ArrayObjectAdapter allAdapter = new ArrayObjectAdapter(new MovieCardPresenter());
        categoryAdapters.put(CATEGORY_ALL, allAdapter);
        rowsAdapter.add(new ListRow(allHeader, allAdapter));

        // 添加顶级分类
        for (Category category : categories) {
            if (category.getTypePid() != 0) {
                HeaderItem header = new HeaderItem(category.getTypeId(), category.getTypeName());
                ArrayObjectAdapter adapter = new ArrayObjectAdapter(new MovieCardPresenter());
                categoryAdapters.put(category.getTypeId(), adapter);
                rowsAdapter.add(new ListRow(header, adapter));
            }
        }

        // 加载各分类的影片
        loadMoviesByCategory(CATEGORY_ALL);
        for (Category category : categories) {
            if (category.getTypePid() != 0) {
                loadMoviesByCategory(category.getTypeId());
            }
        }
    }
    
    /**
     * 按分类加载影片
     * @param categoryId 分类ID
     */
    private void loadMoviesByCategory(int categoryId) {
        viewModel.setSelectedCategory(categoryId);
        viewModel.getMovieList(1).observe(getViewLifecycleOwner(), result -> {
            if (result.isSuccess() && result.getData() != null) {
                ArrayObjectAdapter adapter = categoryAdapters.get(CATEGORY_ALL);
                if (adapter != null) {
                    adapter.clear();
                    for (Movie movie : result.getData()) {
                        adapter.add(movie);
                    }
                }
                
                // 根据类型分类影片
                for (Movie movie : result.getData()) {
                    int typeId = movie.getTypeId();
                    if (categoryAdapters.containsKey(typeId)) {
                        ArrayObjectAdapter typeAdapter = categoryAdapters.get(typeId);
                        if (typeAdapter != null) {
                            typeAdapter.add(movie);
                        }
                    }
                }
            } else {
                Toast.makeText(getContext(), "加载影片失败: " + result.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
} 